package com.marvels.approve.loan.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.fintech.common.util.ProductUtils;
import com.github.pagehelper.util.StringUtil;
import com.marvels.approve.common.dto.InsurancePolicyDTO;
import com.marvels.approve.common.service.ApproveIStateDetailedService;
import com.marvels.approve.common.service.McamLoanApplyInfoCommonService;
import com.marvels.approve.loan.dto.LoanSamplingDTO;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.ILoanSamplingService;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.approve.loan.service.McamLoanInsurancePolicyInfoService;
import com.marvels.approve.manager.dto.OpinionDTO;
import com.marvels.approve.manager.dto.OpinionTypeDTO;
import com.marvels.approve.manager.service.IOpinionService;
import com.marvels.approve.manager.service.IOpinionTypeService;
import com.marvels.approve.process.dao.ILoanApplyCaseDao;
import com.marvels.approve.process.dto.CompleteProcessDTO;
import com.marvels.approve.process.dto.LoanApplyCaseDTO;
import com.marvels.approve.process.dto.ProcessApproveDTO;
import com.marvels.approve.process.service.IProcessService;
import com.marvels.approve.process.service.TaskProcessService;
import com.marvels.common.constants.CaseNodeConstant;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;

/**
 * 审计
 * @author FJJF1
 *
 */
@Service
public class LoanSamplingServiceImpl implements ILoanSamplingService {
	@Autowired
	private ILoanApplyCaseDao loanApplyCaseDao ;
	@Autowired
	private IOpinionTypeService opinionTypeService ;
	@Autowired
	private IMcamLoanApplyInfoService mcamLoanApplyInfoService;
	@Autowired
	private McamLoanApplyInfoCommonService mcamLoanApplyInfoCommonService;
	@Autowired
	private IProcessService processService;
	@Autowired
	private ApproveIStateDetailedService stateDetailedService;
	@Autowired
	private IOpinionService opinionService;
	@Autowired
	private McamLoanInsurancePolicyInfoService mcamLoanInsurancePolicyInfoService;
	@Autowired
    private TaskProcessService  taskProcessService;
	@Value("${config.properties.path}")
	private String filePath;
	@Override
	public LoanSamplingDTO findSampling(LoanSamplingDTO loanSamplingDTO) throws MarvelsBusinessException {
		//查询征信审计阶段信息
		if(loanSamplingDTO == null || loanSamplingDTO.getLoanId() == null ) {
			throw new MarvelsBusinessException("查询征信审计阶段信息条件不能为空"+loanSamplingDTO);
		}
		String loanId = loanSamplingDTO.getLoanId();
		LoanApplyCaseDTO loanApplyCase = loanApplyCaseDao.getEntityByLoanId(loanId);
		if(loanApplyCase==null) {
			throw new MarvelsBusinessException("工单不存在loanId:"+loanId);
		}
		if(!CaseNodeConstant.WOSAMPLING.getCode().equals(loanApplyCase.getCurNodeCode())) {
			throw new MarvelsBusinessException("工单节点在"+loanApplyCase.getCurNodeCode()+"不正确,loanId:"+loanId);
		} 
		UserDTO user = CacheUtils.getCacheUser();
		String userCode = user.getUserCode();
		if(userCode==null || !userCode.equals(loanApplyCase.getAssignee())) {
			throw new MarvelsBusinessException("工单属于"+loanApplyCase.getAssignee()+",请确认工单所属,loanId:"+loanId);
		}
		loanSamplingDTO.setLoanApplyCase(loanApplyCase);
		//初始化类型选项
		Map<Integer,List<OpinionTypeDTO>> opinionTypes = this.opinionTypeService.getOpinionTypes(CaseNodeConstant.WOSAMPLING.getCode());
		loanSamplingDTO.setOpinionTypes(opinionTypes);
		//日志加意见
		//LOG
		List<OpinionDTO>  logs = opinionService.selectApproveResultLogByLoanId(loanApplyCase);
		loanSamplingDTO.setLogs(logs);
		// OPINOIN
		List<OpinionDTO> opinions = opinionService.selectOpinionsByCaseVersion(loanApplyCase);
		loanSamplingDTO.setOpinions(opinions);
		return loanSamplingDTO;
	}
	
	@Override
	public LoanSamplingDTO saveSampling(LoanSamplingDTO loanSamplingDTO) throws MarvelsBusinessException {
		// 保存征信审计信息
		String loanId = loanSamplingDTO.getLoanId();
		LoanApplyCaseDTO loanApplyCase = getLoanApplyCase(loanId);
		McamLoanApplyInfoDTO loanApplyInfo = getLoanApplyInfo(loanId);
		//保存相关日志
		opinionService.saveOpinions(loanApplyCase,loanApplyInfo, loanSamplingDTO.getProcessResult()
				,loanSamplingDTO.getProcessOpinions(),loanSamplingDTO.getViolationOpinion(),loanSamplingDTO.getReturnAppOpinions(),loanSamplingDTO.getSamplingOpinionTypes()
				,loanSamplingDTO.getSamplingOpinionContent(),loanSamplingDTO.getViolationOptionContent(),loanSamplingDTO.getReturnAppOpinionContent());
		return loanSamplingDTO;
	}
	//修改进件状态
	private void editLoanApplyInfo(McamLoanApplyInfoDTO loanApplyInfo , LoanApplyCaseDTO loanApplyCase) throws MarvelsBusinessException {
		String nodeCode = loanApplyCase.getCurNodeCode();
		//feign调用
		String stateId = stateDetailedService.queryStateDetailedByNodeCode(nodeCode);
		if(stateId == null) {
			throw new MarvelsBusinessException("新节点"+nodeCode+"无法获取进件节点号"+stateId);
		}
		String oldStatus = loanApplyInfo.getStatus();
		loanApplyInfo.setOldStatus(oldStatus);
		loanApplyInfo.setStatus(stateId);
		this.mcamLoanApplyInfoService.updateMcamLoanApplyInfoByLoanId(loanApplyInfo);
	}
	private McamLoanApplyInfoDTO getLoanApplyInfo(String loanId) throws MarvelsBusinessException {
		// 查询贷款信息
		if (loanId == null) {
			throw new MarvelsBusinessException("查询贷款信息条件不能为空" + loanId);
		}
		McamLoanApplyInfoDTO loanApplyInfo = this.mcamLoanApplyInfoService.findMcamLoanApplyInfo(loanId);
		if (loanApplyInfo == null) {
			throw new MarvelsBusinessException("贷款信息不存在loanId:" + loanId);
		}
		if ( !LoanStateConstant.C00.equals(loanApplyInfo.getStatus()) && !LoanStateConstant.C01.equals(loanApplyInfo.getStatus()) ) {
			throw new MarvelsBusinessException("贷款信息状态不是审计复核阶段，请确认数据是否正确！status:"+loanApplyInfo.getStatus()+"\tloanId:" + loanId);
		}
		return loanApplyInfo;
	}
	private LoanApplyCaseDTO getLoanApplyCase(String loanId) throws MarvelsBusinessException {
		// 查询复核信息
		if (loanId == null) {
			throw new MarvelsBusinessException("查询征信审计阶段信息条件不能为空" + loanId);
		}
		LoanApplyCaseDTO loanApplyCase = loanApplyCaseDao.getEntityByLoanId(loanId);
		if (loanApplyCase == null) {
			throw new MarvelsBusinessException("工单不存在loanId:" + loanId);
		}
		if (!CaseNodeConstant.WOSAMPLING.getCode().equals(loanApplyCase.getCurNodeCode())) {
			throw new MarvelsBusinessException("工单节点在" + loanApplyCase.getCurNodeCode() + "不正确,loanId:" + loanId);
		}
		return loanApplyCase;
	}

	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	public LoanSamplingDTO complateSampling(LoanSamplingDTO loanSamplingDTO) throws MarvelsBusinessException {
		// 复核征信审计信息
		// 保存征信审计信息
		String loanId = loanSamplingDTO.getLoanId();
		LoanApplyCaseDTO loanApplyCase = getLoanApplyCase(loanId);
		McamLoanApplyInfoDTO loanApplyInfo = getLoanApplyInfo(loanId);
		
		//保存相关日志
		opinionService.saveOpinions(loanApplyCase,loanApplyInfo,loanSamplingDTO.getProcessResult()
				,loanSamplingDTO.getProcessOpinions(),loanSamplingDTO.getViolationOpinion(),loanSamplingDTO.getReturnAppOpinions(),loanSamplingDTO.getSamplingOpinionTypes()
				,loanSamplingDTO.getSamplingOpinionContent(),loanSamplingDTO.getViolationOptionContent(),loanSamplingDTO.getReturnAppOpinionContent());
		
		// 流转activiti
		CompleteProcessDTO completeProcessDTO = new CompleteProcessDTO();
		completeProcessDTO.setLoanId(loanId);
//		Map<String, Object> variables = new HashMap();
		ProcessApproveDTO processApproveDto = new ProcessApproveDTO();
//		variables.put("processResult", loanSamplingDTO.getProcessResult());
		processApproveDto.setProcessResult(loanSamplingDTO.getProcessResult());
//		completeProcessDTO.setVariables(variables);
		completeProcessDTO.setProcessApproveDto(processApproveDto);
		loanApplyCase = processService.completeLoanApplyCase(completeProcessDTO);
		// 更改进件数据
		modifyStatus(loanApplyInfo, loanApplyCase);
		return loanSamplingDTO;
	}
	
	//征信 状态流转
	private void modifyStatus(McamLoanApplyInfoDTO loanApplyInfo,LoanApplyCaseDTO loanApplyCase)throws MarvelsBusinessException {
		String status = loanApplyInfo.getStatus();
		String nextStatus = "";
		String curNodeCode = loanApplyCase.getCurNodeCode();
		String assignee = loanApplyCase.getAssignee();
		if(CaseNodeConstant.WOSAMPLING.getCode().equals(curNodeCode)) {
			nextStatus = LoanStateConstant.C01;
			if(StringUtil.isEmpty(assignee)) {
				nextStatus = LoanStateConstant.C01;
			}else {
				nextStatus = LoanStateConstant.C00;
			}
		}else if(CaseNodeConstant.WOINTERVIEW.getCode().equals(curNodeCode)) {
			nextStatus = LoanStateConstant.P01;
			//生成祁安保险
			generateAssureBx(loanApplyInfo.getLoanId());
		}else if(StringUtils.equals(CaseNodeConstant.WOAPPROVAL.getCode(), curNodeCode)){//退单到审批复核
			if(StringUtil.isEmpty(assignee)) {
				nextStatus = LoanStateConstant.S01;
			}else {
				nextStatus = LoanStateConstant.S00;
			}
		}
		//全流程
		if(StringUtil.isNotEmpty(nextStatus)) {
			mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanApplyInfo.getLoanId(), nextStatus, status, null);
		}
	}
	
	public void generateAssureBx(String loanId) throws MarvelsBusinessException{
//		McamLoanApplyInfoDTO loan = taskProcessService.getLoanInfo(loanId);
//		String status = loan.getStatus();
//		if(!LoanStateConstant.P01.equals(status)) {
//			return ;
//		}
//		InsurancePolicyDTO bxDto = mcamLoanInsurancePolicyInfoService.selectInsuranceByLoanIdAndCompany(loanId, "qabx");
//		if(loan == null ||  bxDto != null) {
//			MarvelsLogUtil.getInstance().info("loanId " + loanId+"已经存在保单");
//			return;
//		}
		//获取担保费率配置
//		if(!isValid(loan)){
//			MarvelsLogUtil.getInstance().info("旧的单子loanId " + loanId+"不用再生产保单");
//			return;
//		}
		//保存保单
//		mcamLoanInsurancePolicyInfoService.saveAssureBx(loan,true);
		
	}
	
}
